<?php
class LinksController extends AppController {

	var $name = 'Links';
	var $helpers = array('Html', 'Form', 'Text', 'Javascript', 'Ajax', 'Cache' );
	
	var $cacheAction = "1 hour";
	
	function _findDistinctTags() {
		return $this->Link->findAll(null,'DISTINCT `Link`.`tag`', 'Link.tag DESC');
		//$posts = $this->findAll('Post.tag NOT LIKE ""', array('DISTINCT `Post`.`tag`'), 'Post.tag DESC');
	}
	function autocomplete() {
	    $this->set('links', $this->_findDistinctTags());
	    $this->layout = "ajax";
	}
	
	function getLinkList() {
		$links = $this->_findDistinctTags();
		$formated_links = array();
		foreach ($links as $link) {
			$tagname = $link['Link']['tag'];
			$formated_links[$tagname] = array('tag'=>$tagname, 'Links'=> $this->Link->findAll(array('Link.tag' => $tagname),null, 'Link.title DESC')); 
		}
		return $formated_links;
	}
	
	function admin_index() {
		$this->pre_admin();
		$this->Link->recursive = 0;
		$this->set('links', $this->Link->findAll(null, null, 'Link.tag ASC, Link.id ASC'));
	}
	

	function admin_view($id = null) {
		$this->pre_admin();
		if(!$id) {
			$this->Session->setFlash('Invalid id for Link.');
			$this->redirect('/admin/links/index');
		}
		$this->set('link', $this->Link->read(null, $id));
	}

	function admin_addedit($id = null) {
		$this->pre_admin();
		if(empty($this->data)) {
			if($id) {
				$this->data = $this->Link->read(null, $id);
			}
		} else {
			$this->cleanUpFields();
			if($this->Link->save($this->data)) {
				$this->Session->setFlash('The Link has been saved');
				if(!$this->data['Link']['id']) {
					$new_id = $this->Link->getInsertID();
					$this->Session->setFlash('The new Link has been saved!');
					$this->redirect('/admin/links/addedit/' . $new_id);
				}
			} else {
				$this->Session->setFlash('Please correct errors below.');
			}
		}
	}

	function admin_delete($id = null) {
		if(!$id) {
			$this->Session->setFlash('Invalid id for Link');
			$this->redirect('/admin/links/index');
		}
		if($this->Link->del($id)) {
			$this->Session->setFlash('The Link deleted: id '.$id.'');
			$this->redirect('/admin/links/index');
		}
	}

}
?>